package com.the9tcat.funnyalarmclock.oauth;

import android.app.Dialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

/**
 * @author jianhpin
 */
public class OauthDialog extends Dialog {
    
    private Context mContext;
    
    private OauthListener mListener;
    
    /**
     * @param context
     */
    public OauthDialog(Context context, String url, OauthListener listener) {
        super(context);
        mContext = context;
        mListener = listener;
        setTitle("用户验证");
        RelativeLayout layout = new RelativeLayout(mContext);
        setContentView(layout);
        WebView web = new WebView(mContext);
        layout.addView(web);
        web.setWebViewClient(new OauthWebViewClient());
        web.getSettings().setJavaScriptEnabled(true);
        web.setHorizontalScrollBarEnabled(false);
        web.setVerticalScrollBarEnabled(false);
        web.loadUrl(url);
    }
    
    class OauthWebViewClient extends WebViewClient {

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
            if (url.contains("cancel")) {
                dismiss();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            if (!isShowing()) {
//                show();
//            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith(OauthConfig.oauth_callback)) {
                Uri uri = Uri.parse(url);
                String oauth_token = uri.getQueryParameter("oauth_token");
                String oauth_verifier = uri.getQueryParameter("oauth_verifier");
                Bundle data = new Bundle();
                data.putString(OauthConfig.extra_oauth_token, oauth_token);
                data.putString(OauthConfig.extra_oauth_verifier, oauth_verifier);
                mListener.onComplete(data);
                dismiss();
            }
            return true;
        }
    }
}
